import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  NavBar,
  Result,
  Button,
  Space,
  Dialog,
  Toast,
  Divider
} from 'antd-mobile';
import {
  CheckCircleFill,
  CloseCircleFill,
  ClockCircleFill
} from 'antd-mobile-icons';
import './Payment.css';
import { useRequest } from 'ahooks';
import { getOrders } from '../../api/dashboard';
import { updateOrder } from '../../api/store';

// 支付页面
const Payment = () => {
  const navigate = useNavigate();
  const { orderId } = useParams();
  const [order, setOrder] = useState(null);
  const [loading, setLoading] = useState(true);
  const [payStatus, setPayStatus] = useState('pending'); // pending, success, fail
  const [remainingTime, setRemainingTime] = useState(15 * 60); // 15分钟，以秒为单位

  const { runAsync: getOrdersAsync } = useRequest(getOrders, { manual: true });
  const { runAsync: updateOrderAsync } = useRequest(updateOrder, { manual: true });

  // 获取订单数据
  useEffect(() => {
    const fetchOrder = async () => {
      setLoading(true);

      try {
        // 通过API获取订单数据
        const orders = await getOrdersAsync({ params: { id: 1 } });
        const foundOrder = orders.find(o => o.id === orderId);

        if (!foundOrder) {
          Toast.show({
            icon: 'fail',
            content: '订单不存在',
          });
          navigate('/home');
          return;
        }

        setOrder(foundOrder);
      } catch (error) {
        console.error('获取订单失败:', error);
        Toast.show({
          icon: 'fail',
          content: '获取订单数据失败',
        });
        navigate('/home');
      }
      setLoading(false);
    };

    fetchOrder();
  }, [orderId, navigate, getOrdersAsync]);

  // 倒计时效果
  useEffect(() => {
    if (payStatus !== 'pending') return;

    const timer = setInterval(() => {
      setRemainingTime(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          handleCountdownFinish();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [payStatus]);

  // 格式化剩余时间
  const formatRemainingTime = () => {
    const minutes = Math.floor(remainingTime / 60);
    const seconds = remainingTime % 60;
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  };

  // 模拟支付成功
  const handlePaySuccess = async () => {
    setPayStatus('success');

    try {
      // 通过API更新订单状态
      await updateOrderAsync({
        id: orderId,
        status: 'paid',
        payTime: new Date().toISOString()
      });

      // 更新本地订单状态
      setOrder(prev => ({
        ...prev,
        status: 'paid',
        payTime: new Date().toISOString()
      }));

      // 显示支付成功
      Toast.show({
        icon: 'success',
        content: '支付成功',
      });
    } catch (error) {
      console.error('更新订单状态失败:', error);
      Toast.show({
        icon: 'fail',
        content: '支付状态更新失败',
      });
    }
  };

  // 模拟支付失败
  const handlePayFail = () => {
    setPayStatus('fail');

    Toast.show({
      icon: 'fail',
      content: '支付失败',
    });
  };

  // 取消支付
  const handleCancel = () => {
    Dialog.confirm({
      content: '确认取消支付吗？',
      onConfirm: () => {
        navigate('/order/list');
      },
    });
  };

  // 处理倒计时结束
  const handleCountdownFinish = () => {
    if (payStatus === 'pending') {
      setPayStatus('fail');
      Toast.show({
        icon: 'fail',
        content: '支付超时，请重新下单',
      });
    }
  };

  // 返回上一页
  const back = () => {
    if (payStatus === 'success') {
      navigate('/order/detail/' + orderId);
    } else {
      Dialog.confirm({
        content: '确认离开支付页面吗？',
        onConfirm: () => {
          navigate(-1);
        },
      });
    }
  };

  // 渲染支付方式图标
  const renderPaymentIcon = () => {
    if (!order) return null;

    switch (order.paymentMethod) {
      case 'alipay':
        return <div className="payment-icon alipay-icon">支</div>;
      case 'wechat':
        return <div className="payment-icon wechat-icon">微</div>;
      case 'cod':
        return <div className="payment-icon cod-icon">付</div>;
      default:
        return null;
    }
  };

  // 渲染支付状态
  const renderPayStatus = () => {
    switch (payStatus) {
      case 'success':
        return (
          <Result
            status='success'
            title='支付成功'
            description={`支付金额: ¥${order?.totalPrice?.toFixed(2)}`}
          />
        );
      case 'fail':
        return (
          <Result
            status='error'
            title='支付失败'
            description='请重新尝试支付或选择其他支付方式'
          />
        );
      default:
        return (
          <div className="payment-pending">
            <div className="payment-method">
              {renderPaymentIcon()}
              <div className="payment-name">
                {order?.paymentMethod === 'alipay' ? '支付宝' :
                  order?.paymentMethod === 'wechat' ? '微信支付' : '货到付款'}
              </div>
            </div>
            <div className="payment-amount">
              ¥{order?.totalPrice?.toFixed(2)}
            </div>
            <div className="payment-countdown">
              <ClockCircleFill /> 支付剩余时间：{formatRemainingTime()}
            </div>
            <Divider />
            <div className="payment-tips">
              <p>请使用{order?.paymentMethod === 'alipay' ? '支付宝' :
                order?.paymentMethod === 'wechat' ? '微信' : '现金'}完成支付</p>
              <p className="tip-highlight">本页面仅作演示，点击下方按钮模拟支付结果</p>
            </div>
          </div>
        );
    }
  };

  // 渲染底部按钮
  const renderFooterButtons = () => {
    switch (payStatus) {
      case 'success':
        return (
          <Space direction='vertical' block>
            <Button
              color='primary'
              block
              onClick={() => navigate('/order/detail/' + orderId)}
            >
              查看订单
            </Button>
            <Button
              block
              onClick={() => navigate('/home')}
            >
              返回首页
            </Button>
          </Space>
        );
      case 'fail':
        return (
          <Space direction='vertical' block>
            <Button
              color='primary'
              block
              onClick={() => setPayStatus('pending')}
            >
              重新支付
            </Button>
            <Button
              block
              onClick={() => navigate('/order/list')}
            >
              查看订单
            </Button>
          </Space>
        );
      default:
        return (
          <Space direction='vertical' block>
            <div className="mock-buttons">
              <Button
                color='primary'
                onClick={handlePaySuccess}
              >
                模拟支付成功
              </Button>
              <Button
                color='danger'
                onClick={handlePayFail}
              >
                模拟支付失败
              </Button>
            </div>
            <Button
              block
              onClick={handleCancel}
            >
              取消支付
            </Button>
          </Space>
        );
    }
  };

  if (loading || !order) {
    return (
      <div className="loading-container">
        <div className="loading-spinner">加载中...</div>
      </div>
    );
  }

  return (
    <div className="payment-container">
      {/* 导航栏 */}
      <NavBar onBack={back}>
        {payStatus === 'pending' ? '订单支付' :
          payStatus === 'success' ? '支付成功' : '支付失败'}
      </NavBar>

      {/* 支付状态 */}
      <div className="payment-content">
        {renderPayStatus()}
      </div>

      {/* 底部按钮 */}
      <div className="payment-footer">
        {renderFooterButtons()}
      </div>
    </div>
  );
};

export default Payment; 